<?php


namespace app\badmin\controller;


use app\common\controller\BadminController;
use app\common\lib\RespCode;
use custom\Err;
use custom\Redis;
use oss\Oss;
use think\Exception;
use think\facade\Env;

class Upload extends BadminController {

    function img() {
        try {
            $file = request()->file('file');
            $type = input('type');
            $img_ext = 'jpg,png,gif,jpeg,bmp';
            $video_ext = 'mp4,mpeg,baiavi,navi,asf,mov,3gp,wmv,divx,xvid,rm,rmvb,flv,f4v';
            if (empty($type)) {
                throw new Exception('文件类型不能为空', RespCode::PARAMS_ERR);
            }
            if (!in_array($type, ['agent_cover', 'agent_voice', 'company_video', 'video_cover', 'house_table_img'])) {
                throw new Exception('错误的文件类型', RespCode::PARAMS_ERR);
            }
            if (empty($file)) {
                throw new Exception('请选择文件', RespCode::FILE_EMPTY);
            }
            //经纪人头像
            if ($type == 'agent_cover') {
                if (!$file->check(['size' => 5242880, 'ext' => $img_ext])) {
                    throw new Exception($file->getError(),RespCode::PARAMS_ERR);
                }
            }
            //经纪人语音
            if ($type == 'agent_voice') {
                if (!$file->check(['size' => 5242880, 'ext' => 'mp3'])) {
                    throw new Exception($file->getError(),RespCode::PARAMS_ERR);
                }
            }
            //公司视频
            if ($type == 'company_video') {
                if (!$file->check(['size' => 8388608, 'ext' => $video_ext])) {
                    throw new Exception($file->getError(),RespCode::PARAMS_ERR);
                }
            }
            //公司视频封面
            if ($type == 'video_cover') {
                if (!$file->check(['size' => 5242880, 'ext' => $img_ext])) {
                    throw new Exception($file->getError(),RespCode::PARAMS_ERR);
                }
            }
            //房源表图片
            if ($type == 'house_table_img') {
                if (!$file->check(['size' => 5242880, 'ext' => $img_ext])) {
                    throw new Exception($file->getError(),RespCode::PARAMS_ERR);
                }
            }
            $info = $file->getInfo();
            $oss = Oss::getInstance();
            if(Env::get ('app.dev','dev')=='dev') $dir="test/badmin/{$type}";
            else $dir="badmin/{$type}";
            $filename = $oss->createFilename($dir, get_ext($info['name']));
            if ($oss->uploadFile($info['tmp_name'])) {
                $redisModel = Redis::getInstance();
                $redisModel->hset('upload_file_badmin', date('Y-m-d'), $type);
                return $this->resData('success', ['url' => $filename]);
            }
        } catch (Exception $e) {
            return $this->resErr($e->getMessage(), $e->getCode());
        }
    }

}